package com.lhlk.初始化;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

/**
 * 通过反射，动态创建对象
 */
public class 通过反射创建对象 {
    public static void main(String[] args) throws ClassNotFoundException {
        try {
            Class user=Class.forName("com.lhlk.初始化.User");
            try {
                //实际是通过无参构造器构造
                User user1 = (User)user.newInstance();
                System.out.println(user1);
            } catch (InstantiationException e) {
                e.printStackTrace();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }



        //通过构造器区构造对象
        Class User=Class.forName("com.lhlk.初始化.User");
        try {
            Constructor dec = User.getDeclaredConstructor(String.class, Integer.class);
            User user =(User)dec.newInstance("张三", 23);
            System.out.println(user);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

    }
}
